Page({
  data: {
      userInfo: null,
      keywords: '',
      skills: '',
      loading: false,
      currentSubscription: null,
      notifications: [],
      baseUrl: 'http://localhost:3000'
  },

  onLoad: function() {
      this.loadUserInfo().then(() => {
          this.loadCurrentSubscription();
          this.loadNotifications();
      }).catch((error) => {
          console.error('Error loading user info:', error);
          wx.showToast({
              title: '加载用户信息失败',
              icon: 'none'
          });
      });
  },

  loadUserInfo: function() {
      return new Promise((resolve, reject) => {
          const userInfo = wx.getStorageSync('userInfo');
          if (userInfo) {
              this.setData({ userInfo }, () => {
                  resolve();
              });
          } else {
              wx.redirectTo({
                  url: '/pages/login/login'
              });
              reject(new Error('User info not found'));
          }
      });
  },

  loadCurrentSubscription: function() {
      const { userInfo } = this.data;
      if (!userInfo) return;

      wx.request({
          url: `${this.data.baseUrl}/api/users/${userInfo.id}/subscriptions`,
          method: 'GET',
          success: (res) => {
              if (res.data && res.data.length > 0) {
                  this.setData({
                      currentSubscription: res.data[0],
                      keywords: res.data[0].keywords || '',
                      skills: res.data[0].skills || ''
                  });
              }
          },
          fail: (err) => {
              console.error('获取订阅信息失败:', err);
              wx.showToast({
                  title: '获取订阅信息失败',
                  icon: 'none'
              });
          }
      });
  },

  loadNotifications: function() {
      const { userInfo } = this.data;
      if (!userInfo) return;

      wx.request({
          url: `${this.data.baseUrl}/api/messages?userId=${userInfo.id}&type=received`,
          method: 'GET',
          success: (res) => {
              this.setData({ notifications: res.data });
          },
          fail: (err) => {
              console.error('获取通知信息失败:', err);
              wx.showToast({
                  title: '获取通知信息失败',
                  icon: 'none'
              });
          }
      });
  },

  onKeywordsInput: function(e) {
      this.setData({
          keywords: e.detail.value
      });
  },

  onSkillsInput: function(e) {
      this.setData({
          skills: e.detail.value
      });
  },

  submitSubscription: function() {
      const { userInfo, keywords, skills } = this.data;

      if (!userInfo) {
          wx.showToast({
              title: '请先登录',
              icon: 'none'
          });
          return;
      }

      if (!keywords.trim() && !skills.trim()) {
          wx.showToast({
              title: '请至少填写一项',
              icon: 'none'
          });
          return;
      }

      this.setData({ loading: true });

      wx.request({
          url: `${this.data.baseUrl}/api/users/${userInfo.id}/subscriptions`,
          method: 'POST',
          data: {
              keywords: keywords.trim(),
              skills: skills.trim()
          },
          success: (res) => {
              if (res.data.success) {
                  wx.showToast({
                      title: '订阅成功',
                      icon: 'success'
                  });
                  // 立即更新本地状态
                  this.setData({
                      currentSubscription: {
                          keywords: keywords.trim(),
                          skills: skills.trim()
                      },
                      keywords: '',
                      skills: ''
                  }, () => {
                      // 重新加载订阅信息以确保是最新的
                      this.loadCurrentSubscription();
                  });
              } else {
                  wx.showToast({
                      title: '订阅失败',
                      icon: 'none'
                  });
              }
          },
          fail: (err) => {
              console.error('提交订阅失败:', err);
              wx.showToast({
                  title: '提交失败',
                  icon: 'none'
              });
          },
          complete: () => {
              this.setData({ loading: false });
          }
      });
  }
});